/**
 * 
 */
package arisufascion.com.activity;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import arisufascion.com.AbstractActivity;
import arisufascion.com.MainApplication;
import arisufascion.com.R;
import arisufascion.com.activity.ActivityCart.getProductsFromServer;
import arisufascion.com.compone.LoadMoreListView.OnLoadMoreListener;
import arisufascion.com.constant.Constants;
import arisufascion.com.constant.Utils;
import arisufascion.com.constant.WriteLog;
import arisufascion.com.db.MySharePreferences;
import arisufascion.com.db.ProductDataSource;
import arisufascion.com.model.Product;
import arisufascion.com.model.Profile;
import arisufascion.com.network.RequestTask;
import arisufascion.com.tabs.BadgeTabManager;

import com.androidquery.AQuery;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

/**
 * @author Kelvin
 * 
 */
public class ActivityComfirmCheckOut extends AbstractActivity {
	private MainApplication apps;
	private int page = 1;
	private LayoutInflater inflater;
	private boolean isLoading = true;
	private ProgressDialog dialog;
	private List<Product> products = new ArrayList<Product>();
	private int categories_id;
	private ProductDataSource dbAdapter;
	private TableRow row;
	private TableLayout tbl_product;
	private AQuery aq;
	private float total_result_price = 0;
	private float total_price = 0;
	private TextView txt_total_result_price, txt_total,txt_user;
	private EditText edittext_customer_comment;
	private String order_id;
	private EditText edit_company_name, edit_email, edit_name, edit_address,
			edit_phone;

	private EditText edit_shipping_company_name, edit_shipping_email,
			edit_shipping_name, edit_shipping_address, edit_shipping_phone;
	private Button btn_edit_billing, btn_edit_shipping;

	protected static final int REFRESH = 0;

	private Handler _hRedraw;

	// define config for payment
	// set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
	// set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
	// from https://developer.paypal.com
	// set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without
	// communicating to PayPal's servers.
	private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;

	// note that these credentials will differ between live & sandbox
	// environments.
	private static final String CONFIG_CLIENT_ID = "AZJ25BDyG-EHXSIZ3-qIEDwBFZN18zTW7dRpYRRBfHtENvZ_hVKyiZbbb1Ts";
	// when testing in sandbox, this is likely the -facilitator email address.
	private static final String CONFIG_RECEIVER_EMAIL = "tuan.pakureserve-facilitator@gmail.com";
	private CheckBox checkBoxTermns;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_confirm_checkout);
		apps = (MainApplication) getApplication();
		aq = new AQuery(getParent());

		_hRedraw = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case REFRESH:
					redrawEverything();
					break;
				}
			}
		};

		dbAdapter = new ProductDataSource(getParent());
		dbAdapter.open();

		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btn_privacy).setOnClickListener(onClick);
		findViewById(R.id.btn_wholesale).setOnClickListener(onClick);
		findViewById(R.id.btn_shipping).setOnClickListener(onClick);

		findViewById(R.id.btnCheckOut).setOnClickListener(eventOnClick);
		findViewById(R.id.btn_continue).setOnClickListener(eventOnClick);
		findViewById(R.id.btn_clear_all).setOnClickListener(eventOnClick);

		findViewById(R.id.btn_edit_billing).setOnClickListener(eventOnClick);
		findViewById(R.id.btn_edit_shipping).setOnClickListener(eventOnClick);

		checkBoxTermns = (CheckBox) findViewById(R.id.checkBoxTermns);
		tbl_product = (TableLayout) findViewById(R.id.tbl_product);
		txt_total_result_price = (TextView) findViewById(R.id.txt_total_result_price);
		txt_total = (TextView) findViewById(R.id.txt_total);
		txt_user = (TextView) findViewById(R.id.txt_user);
		btn_edit_billing = (Button) findViewById(R.id.btn_edit_billing);
		btn_edit_shipping = (Button) findViewById(R.id.btn_edit_shipping);

		edittext_customer_comment= (EditText) findViewById(R.id.edittext_customer_comment);
		edit_company_name = (EditText) findViewById(R.id.edit_company_name);
		edit_email = (EditText) findViewById(R.id.edit_email);
		edit_name = (EditText) findViewById(R.id.edit_name);
		edit_address = (EditText) findViewById(R.id.edit_address);
		edit_phone = (EditText) findViewById(R.id.edit_phone);

		edit_shipping_company_name = (EditText) findViewById(R.id.edit_shipping_company_name);
		edit_shipping_email = (EditText) findViewById(R.id.edit_shipping_email);
		edit_shipping_name = (EditText) findViewById(R.id.edit_shipping_name);
		edit_shipping_address = (EditText) findViewById(R.id.edit_shipping_address);
		edit_shipping_phone = (EditText) findViewById(R.id.edit_shipping_phone);

		Profile pf = dbAdapter.getProfiles().get(0);
		// if(MySharePreferences.getLogin(getParent())){
		// pf=dbAdapter.getProfiles().get(0);
		// }else{
		// pf=apps.getProfileGuest();
		// }

		if(MySharePreferences.getCustomerComment(self)!=null){
			edittext_customer_comment.setText(MySharePreferences.getCustomerComment(self));
		}
		// Billing Edit
		if (pf != null) {
			
			edit_company_name.setText(pf.getCompany_name());
			edit_email.setText(pf.getEmail());
			edit_name.setText(pf.getName());
			edit_address.setText(pf.getAddress_1());
			edit_phone.setText(pf.getPhone_1());

			// Shipping Edit
			edit_shipping_company_name.setText(pf.getCompany_name());
			edit_shipping_email.setText(pf.getEmail());
			edit_shipping_name.setText(pf.getName());
			edit_shipping_address.setText(pf.getAddress_1());
			edit_shipping_phone.setText(pf.getPhone_1());
			if(pf.getUsername()!=null){
			txt_user.setText("Hello "+pf.getUsername());
			}else{
				txt_user.setVisibility(GONE);
			}
		}
		
		// start service for paypal
		Intent intent = new Intent(this, PayPalService.class);

		intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT,
				CONFIG_ENVIRONMENT);
		intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
		intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL,
				CONFIG_RECEIVER_EMAIL);

		startService(intent);

		new getProductsFromServer().execute();

	}

	OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {

		@Override
		public void onLoadMore() {
			new getProductsFromServer().execute();
		}
	};

	public class getProductsFromServer extends
			AsyncTask<Void, Void, List<Product>> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Show Dialog
			// dialog = new ProgressDialog(ActivityComfirmCheckOut.this);
			// dialog.setMessage("Fetching data...");
			// dialog.show();
		}

		@Override
		protected List<Product> doInBackground(Void... params) {
			_hRedraw.sendEmptyMessage(REFRESH);

			return dbAdapter.getProducts();

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(List<Product> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// Dismiss Dialog
			// if (dialog != null && dialog.isShowing()) {
			// dialog.dismiss();
			// }

			if (result != null) {
				total_result_price = 0;
				for (Product product : result) {
					tbl_product.addView(setUp(product),
							new TableLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT));

					total_result_price += product.getQuantity()
							* product.getProduct_price();
				}
				
				  
				txt_total_result_price.setText("$" +  String.format("%.2f", total_result_price));

				txt_total.setText("$" + String.format("%.2f", total_result_price));
				

				int index = 0;
				for (int i = 0; i < dbAdapter.getProducts().size(); i++) {
					index += dbAdapter.getProducts().get(i).getQuantity();
				}

				BadgeTabManager.getInstance().setBadgeAtIndex(index, 1);
			}

		}

		public TableRow setUp(Product product) {
			row = new TableRow(getParent());
			View v;
			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.row_cart, null);
			ImageView iv_cart = (ImageView) v.findViewById(R.id.iv_cart);

			TextView product_name = (TextView) v
					.findViewById(R.id.txt_cart_product_name);

			final TextView product_price = (TextView) v
					.findViewById(R.id.txt_cart_price_product);

			final EditText product_quantity = (EditText) v
					.findViewById(R.id.edittext_cart_quantity);

			ImageButton btn_update = (ImageButton) v
					.findViewById(R.id.btn_update);

			ImageButton btn_delete = (ImageButton) v
					.findViewById(R.id.btn_delete);
			ProgressBar progressBar = (ProgressBar) v
					.findViewById(R.id.progressBar);

			// set data for row
			product_name.setText(product.getProduct_name());
			product_price.setText("$"
					+ String.valueOf(product.getProduct_price()
							* product.getQuantity()));
			product_quantity.setText(String.valueOf(product.getQuantity()));

			try {
				String url = String.format(Constants.SERVER_URL_IMAGES, String
						.valueOf(dbAdapter
								.getAllImageSliders(
										Integer.parseInt(product
												.getVirtuemart_product_id()))
								.get(0).getFile_url()));

				Log.d("Kelvin:", url);

				aq.id(iv_cart).progress(progressBar)
						.image(url, true, true, 0, R.drawable.icon_logo);

			} catch (Exception e) {
				// TODO: handle exception
			}

			btn_update.setTag(btn_update.getId(), product);
			btn_delete.setTag(btn_delete.getId(), product);

			row.addView(v);

			/*
			 * v.setOnClickListener(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { Product pr = (Product)
			 * v.getTag(v.getId()); Bundle bundle = new Bundle();
			 * 
			 * // Toast.makeText(getParent(),pr.getFirstname(), //
			 * Toast.LENGTH_LONG).show();
			 * 
			 * } });
			 */
			btn_update.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					//step 1	
					if(product_quantity.getText().toString().length()>0){
						Product pr = (Product) v.getTag(v.getId());
						//step 2
						if (Integer.parseInt(product_quantity.getText().toString()) > 0) {
							
							//step 3
							if(pr.getColor_quantity()>0){
								
								if (pr.getColor_quantity() >= Integer
										.parseInt(product_quantity.getText().toString())) {

									pr.setQuantity(Integer.parseInt(product_quantity
											.getText().toString()));

									dbAdapter.updateProduct(pr);


									product_price.setText("$"
											+ String.valueOf(pr.getProduct_price()
													* pr.getQuantity()));

									_hRedraw.sendEmptyMessage(REFRESH);
									new getProductsFromServer().execute();

								} else {
									product_quantity.setError(Html
											.fromHtml("<font color='red'>Max quantity reached, new quantity set to "
													+ pr.getColor_quantity() + "</font>"));
								}
							}else{
								if (pr.getQuantity() >= Integer
										.parseInt(product_quantity.getText().toString())) {

									pr.setQuantity(Integer.parseInt(product_quantity
											.getText().toString()));

									dbAdapter.updateProduct(pr);


									product_price.setText("$"
											+ String.valueOf(pr.getProduct_price()
													* pr.getQuantity()));

									_hRedraw.sendEmptyMessage(REFRESH);
									new getProductsFromServer().execute();

								} else {
									product_quantity.setError(Html
											.fromHtml("<font color='red'>Max quantity reached, new quantity set to "
													+ pr.getQuantity() + "</font>"));
								}
							}
						
						} else {
							product_quantity.setError(Html
									.fromHtml("<font color='red'>Minim quantity is 1"
											+ "</font>"));
						}
					}else{
						product_quantity.setError(Html
								.fromHtml("<font color='red'>Please enter quantity"
									+ "</font>"));
					}

					}
				});


			btn_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Product pr = (Product) v.getTag(v.getId());

					Toast.makeText(getParent(), pr.getProduct_name(),
							Toast.LENGTH_LONG).show();

					dbAdapter.deleteProduct(Integer.parseInt(pr
							.getVirtuemart_product_id()),pr.getColor_id());

					_hRedraw.sendEmptyMessage(REFRESH);

					new getProductsFromServer().execute();

				}
			});

			return row;

		}

		OnItemClickListener onItemClick = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long arg3) {
				view.setSelected(true);

				Product pro = (Product) parent.getAdapter().getItem(position);

				Bundle bundle = new Bundle();
			}
		};

	}

	public OnClickListener eventOnClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnCheckOut:
				// store data order befored redirect to paypal checkout
				if (dbAdapter.getProducts().size() > 0) {
					if (checkBoxTermns.isChecked()) {
						new postOrderToServer().execute();
					} else {
						Spanned error_msg = Html
								.fromHtml("<font color='red'>Please check to read termns of services"
										+ "</font>");
						checkBoxTermns.setError(error_msg);
					}
				} else {
					showToast("Cart is empty right now.", Toast.LENGTH_LONG);
				}
				break;
			case R.id.btn_continue:
				finish();

				break;
			case R.id.btn_edit_billing:
				if ("Edit Billing Address".equalsIgnoreCase(btn_edit_billing
						.getText().toString())) {
					setEnableEditBilling(true);

				} else {
					setEnableEditBilling(false);
					// update billing here
					String company_name = edit_company_name.getText()
							.toString();
					String email = edit_email.getText().toString();
					String name = edit_name.getText().toString();
					String address = edit_address.getText().toString();
					String phone = edit_phone.getText().toString();
					Profile pf = new Profile();
					pf.setCompany_name(company_name);
					pf.setEmail(email);
					pf.setName(name);
					pf.setAddress_1(address);
					pf.setPhone_1(phone);
					dbAdapter.updateProfile(pf);

				}

				break;
			case R.id.btn_edit_shipping:
				if ("Edit Shipping Address".equalsIgnoreCase(btn_edit_shipping
						.getText().toString())) {
					setEnableEditShipping(true);

				} else {
					setEnableEditShipping(false);
					// update shipping here

				}
				break;
			case R.id.btn_clear_all:
				dbAdapter.deleteAllProduct();
				tbl_product.removeAllViews();
				new getProductsFromServer().execute();

				break;

			default:
				break;
			}

		}
	};

	public void setEnableEditBilling(boolean isEnable) {

		edit_company_name.setEnabled(isEnable);
		edit_email.setEnabled(isEnable);
		edit_name.setEnabled(isEnable);
		edit_address.setEnabled(isEnable);
		edit_phone.setEnabled(isEnable);
		if (isEnable) {
			btn_edit_billing.setText("Update Billing");
		} else {
			btn_edit_billing.setText("Edit Billing Address");
		}

	}

	public void setEnableEditShipping(boolean isEnable) {
		edit_shipping_company_name.setEnabled(isEnable);
		edit_shipping_email.setEnabled(isEnable);
		edit_shipping_name.setEnabled(isEnable);
		edit_shipping_address.setEnabled(isEnable);
		edit_shipping_phone.setEnabled(isEnable);
		if (isEnable) {
			btn_edit_shipping.setText("Update Shipping");
		} else {
			btn_edit_shipping.setText("Edit Shipping Address");
		}

	}

	public class postOrderToServer extends AsyncTask<Void, Void, Boolean> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// Show Dialog
			dialog = new ProgressDialog(getParent());
			dialog.setMessage("Fetching data...");
			dialog.show();

		}

		@Override
		protected Boolean doInBackground(Void... params) {

			String colorIds = null;
			String colorSizes = null;
			String color_quantity = null;
			String product_ids = null;

			for (int i = 0; i < dbAdapter.getProducts().size(); i++) {

				// set data for all str

				if (i == 0) {
					colorIds = String.valueOf(dbAdapter.getProducts().get(i)
							.getColor_id());
					colorSizes = String.valueOf(dbAdapter.getProducts().get(i)
							.getColor_size());
					color_quantity = String.valueOf(dbAdapter.getProducts()
							.get(i).getQuantity());

					product_ids = dbAdapter.getProducts().get(i)
							.getVirtuemart_product_id();

				} else {
					colorIds += ","
							+ dbAdapter.getProducts().get(i).getColor_id();
					colorSizes += ","
							+ dbAdapter.getProducts().get(i).getColor_size();
					color_quantity += ","
							+ dbAdapter.getProducts().get(i).getQuantity();
					product_ids += ","
							+ Integer.parseInt(dbAdapter.getProducts().get(i)
									.getVirtuemart_product_id());
				}

			}

			try {
				String json = RequestTask.saveOrder(getParent(), dbAdapter
						.getProfiles().get(0), colorIds, colorSizes,
						product_ids, color_quantity,edittext_customer_comment.getText().toString());

				JSONObject jsonObj = new JSONObject(json);

				boolean success = jsonObj.getBoolean("success");
				JSONObject jsOject = jsonObj.getJSONObject("data");
				order_id = jsOject.getString("order_number");

				return success;

			} catch (Exception e) {
				// WriteLog.d(TAG, e.getMessage());
				e.printStackTrace();
			}

			return false;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Dismiss Dialog
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result) {
				PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(
						txt_total.getText().toString().replace("$", "")),
						"USD", order_id);

				Intent intent = new Intent(getParent(), PaymentActivity.class);

				intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT,
						CONFIG_ENVIRONMENT);
				intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID,
						CONFIG_CLIENT_ID);
				intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL,
						CONFIG_RECEIVER_EMAIL);

				// It's important to repeat the clientId here so that the SDK
				// has it if Android restarts your
				// app midway through the payment UI flow.
				intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID,
						CONFIG_CLIENT_ID);
				intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, dbAdapter
						.getProfiles().get(0).getId());
				intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

				startActivityForResult(intent, 0);
			}

		}

	}

	private void redrawEverything() {
		tbl_product.removeAllViews();
		tbl_product.removeAllViewsInLayout();
		tbl_product.invalidate();
		tbl_product.refreshDrawableState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		new getProductsFromServer().execute();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			PaymentConfirmation confirm = data
					.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
			if (confirm != null) {
				try {
					WriteLog.i("paymentExample", confirm.toJSONObject()
							.toString(4));

					WriteLog.i("Result Json Paypal", confirm.toJSONObject()
							.toString());

					// Update order & clear shopping cart

					// new updateOrder().execute();

					dbAdapter.deleteAllProduct();

					// TODO: send 'confirm' to your server for verification.
					// see
					// https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
					// for more details.

				} catch (JSONException e) {
					Log.e("paymentExample",
							"an extremely unlikely failure occurred: ", e);
				}
			}
		} else if (resultCode == Activity.RESULT_CANCELED) {
			Log.i("paymentExample", "The user canceled.");
		} else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
			Log.i("paymentExample",
					"An invalid payment was submitted. Please see the docs.");
		}
	}

	public class updateOrder extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			RequestTask.updateOrder(self, "success");
			return null;
		}

	}

	@Override
	public void onDestroy() {
		stopService(new Intent(this, PayPalService.class));
		super.onDestroy();
	}

}